package com.academy.services;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class BaseService extends AsyncTask<String, Void, String>{
	
	
	private RequestMethod httpMethod;
	private final DefaultHttpClient httpClient = new DefaultHttpClient();
	private ArrayList<NameValuePair> params;
	private ArrayList<NameValuePair> headers;
	private int responseCode;
	private ProgressDialog progressDialog;
	private Context context;
	private ResponseListener responseListener;
	private HttpUriRequest currentRequest;
	private String message;
	public boolean isProgressAvailable = true;
	
	private static final int CONNECTION_TIME_OUT = 10000;
	private static final int SOCKET_TIME_OUT = 10000;
	
	public BaseService(Context context,ResponseListener responseListener,RequestMethod httpMethod){
		this.httpMethod = httpMethod;
		this.context = context;
		params = new ArrayList<NameValuePair>();
		headers = new ArrayList<NameValuePair>();
		this.responseListener = responseListener;
		
	}
	public void addParam(String name, String value)
	{
	    params.add(new BasicNameValuePair(name, value));
	}
	public void addHeader(String name, String value)
	{
	    headers.add(new BasicNameValuePair(name, value));
	}
	

	@Override
	protected void onPreExecute() {
		
		super.onPreExecute();
		if(isProgressAvailable)
		{
		
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("In Progress");
			progressDialog.setCancelable(false);
			progressDialog.show();
		}
		
		

	}
	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}
	@Override
	protected String doInBackground(String... url) {
		String responseResult = null;
		switch(httpMethod) 
        {
            case GET:
            {
                String combinedParams = "";
                if(!params.isEmpty())
                {
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString=null;
						try {
							paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }
              
                HttpGet request = new HttpGet(url[0] + combinedParams);	 
                Log.d("Request URL", url[0] + combinedParams);
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }
                responseResult = executeRequest(request, url[0]);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url[0]);
 
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }
 
                if(!params.isEmpty()){
                    try {
                    		request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					}
                    catch (Exception e) {
						e.printStackTrace();
					}
                }
                responseResult =  executeRequest(request, url[0]);
                break;
            }
        }
    
		return responseResult;
	}
	
	@Override
	protected void onPostExecute(String result) 
	{
		super.onPostExecute(result);
		if(isProgressAvailable)
		{
			progressDialog.dismiss();
		}
		
		if(result != null)
		{
			Log.d("Result ", result);
		}
		
		if(responseCode == 200)
		{
			responseListener.onServiceCompleted(result,currentRequest.getURI().toString());
		}
		else
		{
			responseListener.onServiceFailed(message, currentRequest.getURI().toString());
		}
		httpClient.getConnectionManager().shutdown();
	}
	private String executeRequest(HttpUriRequest request, String url)
    {
		

		currentRequest = request;
        HttpResponse httpResponse;
        String response = null;
        try 
        {
        	
        			HttpParams httpParameters = new BasicHttpParams();
        			HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIME_OUT);
        			HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
        			httpClient.setParams(httpParameters);

        			httpResponse = httpClient.execute(request);
        			responseCode = httpResponse.getStatusLine().getStatusCode();
        			message = httpResponse.getStatusLine().getReasonPhrase();
        			HttpEntity entity = httpResponse.getEntity();        
        			if (entity != null) 
        			{
        				InputStream instream = entity.getContent();
        				response = convertStreamToString(instream);//pass the response
        				instream.close();
        			}
        
            
        } 
        catch (ClientProtocolException e) 
        {	            
        	if(isProgressAvailable)
    		{
    			progressDialog.dismiss();
    		}
    			cancel(true);

        		responseListener.onServiceFailed(e.getLocalizedMessage(), currentRequest.getURI().toString());   
        } 
        catch (IOException e) 
        {
        	if(isProgressAvailable)
    		{
    			progressDialog.dismiss();
    		}
    			cancel(true);

    			System.out.println("expooo>"+e.getLocalizedMessage());
        		responseListener.onServiceFailed(e.getLocalizedMessage(), currentRequest.getURI().toString());   
        }
        return response;
    }
    private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException
    {
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        {
            while ((line = reader.readLine()) != null) 
            {
                sb.append(line + "\n");
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        finally 
        {
            try
            {
                is.close();
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
        return sb.toString();
       
    }
}
